package com.dudu.access;

import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import core.CoreService;

/**
 * 
 * 语音文件格式转换
 */
public class ConvertAudio {

    private static String systemInfo = "Windows";
    static {

	Properties props = System.getProperties(); // 获得系统属性集
	systemInfo = props.getProperty("os.name"); // 操作系统名称
    }

    /**
     * 转化格式
     * 
     * @param sourcePath
     * @param targetPath
     * @return
     */
    public static boolean convert(String sourcePath, String targetPath) {
	File file = new File(sourcePath);
	if (!file.exists()) {
	    CoreService.log.info("转换文件不存在！");
	    try {
		Thread.sleep(100);
	    } catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}
	if (systemInfo.indexOf("Windows") >= 0) {

	    File source = new File(sourcePath);
	    File target = new File(targetPath);
	    AudioAttributes audio = new AudioAttributes();
	    audio.setCodec("libmp3lame");
	    audio.setBitRate(new Integer(128000));
	    audio.setChannels(new Integer(2));
	    audio.setSamplingRate(new Integer(44100));
	    EncodingAttributes attrs = new EncodingAttributes();
	    attrs.setFormat("mp3");
	    attrs.setAudioAttributes(audio);
	    Encoder encoder = new Encoder();

	    try {
		encoder.encode(source, target, attrs);
		return true;
	    } catch (IllegalArgumentException e) {
		e.printStackTrace();
	    } catch (InputFormatException e) {
		e.printStackTrace();
	    } catch (it.sauronsoftware.jave.EncoderException e) {
		e.printStackTrace();
	    }

	} else {
	    try {
		// Runtime.getRuntime().exec(new
		// String[]{"ffmpeg","-i",sourcePath,"-y",targetPath});
		Process process = null;
		String cmd = "ffmpeg -i " + sourcePath + " -y " + targetPath;
		process = Runtime.getRuntime().exec(new String[] { "sh", "-c", cmd });
		StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
		errorGobbler.start();// kick off stderr
		StreamGobbler outGobbler = new StreamGobbler(process.getInputStream(), "STDOUT");
		outGobbler.start();// kick off stdout
		process.waitFor();
		process.destroy();
	    } catch (IOException e) {
		// TODO Auto-generated catch bloc
		e.printStackTrace();
	    } catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}
	try {
	    Thread.sleep(100);
	} catch (InterruptedException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	// 删除源文件
	file.delete();

	return true;

    }

    /**
     * 转化格式 mp3转wav
     * 
     * @param sourcePath
     * @param targetPath
     * @return
     */
    public static boolean convert2(String sourcePath, String targetPath) {
	File file = new File(sourcePath);
	if (!file.exists()) {
	    CoreService.log.info("转换文件不存在！");
	    try {
		Thread.sleep(100);
	    } catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}
	// if (systemInfo.indexOf("Windows") >= 0) {
	if (true) {
	    // windows
	    File source = new File(sourcePath);
	    File target = new File(targetPath);
	    AudioAttributes audio = new AudioAttributes();
	    audio.setCodec("pcm_s16le");
	    audio.setChannels(new Integer(1));// 声道
	    audio.setSamplingRate(new Integer(8000));// 设置音频采样率
	    // 位速 128kbps，音频采样大小16位
	    EncodingAttributes attrs = new EncodingAttributes();
	    attrs.setFormat("wav");
	    attrs.setAudioAttributes(audio);
	    Encoder encoder = new Encoder();

	    try {
		encoder.encode(source, target, attrs);
		return true;
	    } catch (IllegalArgumentException e) {
		e.printStackTrace();
		return false;
	    } catch (InputFormatException e) {
		e.printStackTrace();
		return false;
	    } catch (it.sauronsoftware.jave.EncoderException e) {
		e.printStackTrace();
		return false;
	    }

	} else {
	    // linux
	    // 命令 -i 源文件
	    // -vn 不做视频记录
	    // -ar freq 设置音频采样率（8000）
	    // -ac channels 设置通道 缺省为1（1）
	    // -ab bitrate 设置音频码率（不设置）
	    // -f fmt 强迫采用格式fmt（wav）
	    // -y 覆盖输出文件
	    try {
		Process process = null;
		String cmd = "ffmpeg -i " + sourcePath + "-vn -ar 8000 -ac 1 -f wav -y " + targetPath;
		CoreService.log.info("cmd ...." + cmd);
		// String cmd = "ffmpeg -i " + sourcePath + " -y " + targetPath;
		process = Runtime.getRuntime().exec(new String[] { "sh", "-c", cmd });
		StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
		errorGobbler.start();// kick off stderr
		StreamGobbler outGobbler = new StreamGobbler(process.getInputStream(), "STDOUT");
		outGobbler.start();// kick off stdout
		process.waitFor();
		process.destroy();
	    } catch (Exception e) {
		e.printStackTrace();
	    }
	}
	try {
	    Thread.sleep(100);
	} catch (InterruptedException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	// 删除源文件
	// file.delete();
	return true;
    }

    public static void main(String ager[]) {
	ConvertAudio.convert2("D:/aaaaaaa.mp3", "D:/gaoxstest.wav");
	System.out.println("QQQQQQQQQ");
    }

}
